package com.reggie.console.config;

import org.springframework.format.Formatter;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/**
 * formatter工厂<p>
 * 针对LocalDate、LocalTime、LocalDateTime，提供三种formatter
 *
 * @author yth
 * @since 2023-02-12-14:23
 */
public class MyFormatterFactory {

    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public Formatter<LocalDate> localDateFormatter() {
        return new Formatter<LocalDate>() {
            @Override
            public LocalDate parse(String s, Locale locale) throws ParseException {
                return LocalDate.parse(s, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
            }

            @Override
            public String print(LocalDate localDate, Locale locale) {
                return DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT).format(localDate);
            }
        };
    }

    public Formatter<LocalTime> localTimeFormatter() {
        return new Formatter<LocalTime>() {
            @Override
            public LocalTime parse(String s, Locale locale) throws ParseException {
                return LocalTime.parse(s, DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT));
            }

            @Override
            public String print(LocalTime localTime, Locale locale) {
                return DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT).format(localTime);
            }
        };
    }

    public Formatter<LocalDateTime> localDateTimeFormatter() {
        return new Formatter<LocalDateTime>() {
            @Override
            public LocalDateTime parse(String s, Locale locale) throws ParseException {
                return LocalDateTime.parse(s, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
            }

            @Override
            public String print(LocalDateTime localDateTime, Locale locale) {
                return DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT).format(localDateTime);
            }
        };
    }
}
